package com.action;

import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.dao.BaseDAO;
import com.entity.Userinfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	Userinfo data;

	BaseDAO dao = new BaseDAO();

	public String add() {
		dao.add(data);
		return show();
	}

	public String login() {
//	String pagerandom = ServletActionContext.getRequest().getParameter(
//				"pagerandom");
//		String random = (String) ServletActionContext.getRequest().getSession()
//			.getAttribute("random");
//		if (!pagerandom.equals(random)) {
//			ActionContext.getContext().put("tip","验证码错误!");
//		return "login";
//		} else {
			List<Userinfo> list = dao
					.find(
							"from Userinfo where loginName=? and loginPass=? and userType=?",
							new Object[] { data.getLoginName(),
									data.getLoginPass(), data.getUserType() });
			if (list.size() > 0) {
				Userinfo users = list.get(0);
				ServletActionContext.getRequest().getSession().setAttribute(
						"loginUser", users);
				return "home";
			} else {
				ActionContext.getContext().put("tip","用户名密码错误!");
				return "login";
			}
//		}
 }

	public String reg() {
		data.setUserType("学生");
		dao.add(data);
		return "login";
	}

	public String del() {
		dao.del(dao.findByID(Userinfo.class, data.getId()));
		return show();
	}

	public String show() {
		ActionContext.getContext().put("all", dao.show("from Userinfo"));
		return SUCCESS;
	}

	public String owner() {
		Userinfo userinfo = (Userinfo) ServletActionContext.getRequest()
				.getSession().getAttribute("loginUser");
		ActionContext.getContext().put(
				"all",
				dao.find("from Userinfo where ID=?",
						new Object[] { userinfo.getId() }));
		return SUCCESS;
	}
//系统管理员修改
	public String modify() {
		Object obj = dao.findByID(Userinfo.class, data.getId());
		ActionContext.getContext().put("record", obj);
		return "modify";
	}
	
	public String mod() {
		Object obj = dao.findByID(Userinfo.class, data.getId());
		ActionContext.getContext().put("record", obj);
		return "mod";
	}

	public String update() {
		dao.update(data);
		return show();
	}
	
	public String update1() {
		dao.update(data);
		return owner();
	}

	public Userinfo getData() {
		return data;
	}

	public void setData(Userinfo data) {
		this.data = data;
	}
}
